import { defineStore } from "pinia";
import router from "@/router";
import { TabsState, TabsMenuProps } from "../interface";
import piniaPersistConfig from "@/config/piniaPersist";
import { useKeepAliveStore } from "./keepAlive";

export const useTabsStore = defineStore({
  id: "tabs",
  state: (): TabsState => ({
    tabsList: []
  }),
  getters: {
    /** 当前activity tab */
    getCurrentTab: state => {
      const currentRoute = router.currentRoute.value;
      return state.tabsList.find(item => {
        return item.path === currentRoute.fullPath;
      });
    }
  },
  actions: {
    /** 将已关闭的标签页的组件从keep-alive中移除 */
    delCompFromClosedTabs(closedTabs: TabsMenuProps[]) {
      const keepAliveStore = useKeepAliveStore();
      let compNames = keepAliveStore.keepAliveName.filter(name => closedTabs.every(eveItem => name !== eveItem.name));
      keepAliveStore.setKeepAliveName(compNames);
    },
    initTabs(routes: TabsMenuProps[]) {
      this.tabsList = routes;
    },
    /** 添加Tabs */
    addTabs(tabItem: TabsMenuProps) {
      if (this.tabsList.every(item => item.path !== tabItem.path)) {
        this.tabsList.push(tabItem);
      }
    },
    /** 删除Tabs */
    removeTabs(tabPath: string, isCurrent: boolean = true) {
      const tabsList = this.tabsList;
      if (isCurrent) {
        tabsList.forEach((item, index) => {
          if (item.path !== tabPath) return;
          const nextTab = tabsList[index + 1] || tabsList[index - 1];
          if (!nextTab) return;
          router.push(nextTab.path);
        });
      }
      this.tabsList = tabsList.filter(item => item.path !== tabPath);
    },
    /** 关闭左侧 */
    closeLeftTabs(index: number) {
      this.tabsList = this.tabsList.filter((item, tabIndex) => {
        return tabIndex >= index || !item.closable;
      });
      this.delCompFromClosedTabs(this.tabsList);
    },
    /** 关闭右侧 */
    closeRightTabs(index: number) {
      this.tabsList.splice(index + 1);
      this.delCompFromClosedTabs(this.tabsList);
    },
    /** 关闭多个选项卡 */
    closeMultipleTab(tabsValue?: string) {
      this.tabsList = this.tabsList.filter(item => {
        return item.path === tabsValue || !item.closable;
      });
      this.delCompFromClosedTabs(this.tabsList);
    }
  },
  persist: piniaPersistConfig("tabs")
});
